package com.xhsj.user.hr.process.tbLearningGarden.service;

import com.xhsj.user.hr.process.dto.tbLearningGarden.LearningStatisticsListDto;
import com.xhsj.user.hr.process.hrTransferJob.query.CompletedTransferJobApplyQuery;
import com.xhsj.user.hr.process.tbLearningGarden.entity.TbLearningGardenContentApply;
import com.xhsj.user.hr.process.tbLearningGarden.entity.TbLearningGardenContentLearningRecord;
import com.xhsj.user.hr.process.tbLearningGarden.mapper.TbLearningGardenContentApplyMapper;
import com.xhsj.user.hr.process.tbLearningGarden.mapper.TbLearningGardenContentLearningRecordMapper;
import com.xhsj.user.hr.process.tbLearningGarden.query.LearnedListQuery;
import com.xhsj.user.hr.process.tbLearningGarden.query.LearningStatisticsListQuery;
import com.xhsj.user.hr.process.tbLearningGarden.query.NeedLearningListQuery;
import com.xhsj.user.hr.process.tbLearningGarden.service.TbLearningGardenContentLearningRecordService;
import com.xhsj.user.hr.base.BaseService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.xhsj.user.hr.system.mapper.TbGlobalUserMapper;
import com.xhsj.user.utils.StringUtils;
import com.xhsj.user.hr.process.tbLearningGarden.vo.FindToDayStudyNumberVo;
import com.xhsj.user.utils.StringUtils;
import com.xhsj.user.utils.UserUtils;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Collection;
import java.util.Map;
import java.util.Objects;

import java.time.LocalDate;
import java.util.*;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import java.io.Serializable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import lombok.extern.slf4j.Slf4j;

import static java.math.BigDecimal.ROUND_DOWN;
import static java.math.BigDecimal.ROUND_HALF_DOWN;
import static java.math.BigDecimal.ROUND_UNNECESSARY;

/**
 * <p>
 * 学习园地内容申请-学习记录 服务实现类
 * </p>
 *
 * @author 苏小林
 * @since Nov 24, 2020 9:55:43 AM
 */
@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
//@CacheConfig(cacheNames = "TbLearningGardenContentLearningRecord")
public class TbLearningGardenContentLearningRecordService extends BaseService<TbLearningGardenContentLearningRecordMapper, TbLearningGardenContentLearningRecord>{
    @Autowired
    private TbLearningGardenContentLearningRecordMapper dao;

    @Autowired
    private TbGlobalUserMapper tbGlobalUserMapper;

    @Autowired
    private TbLearningGardenContentApplyMapper tbLearningGardenContentApplyMapper;

	/**
	 * 保存
	 * @author 苏小林
	 * @date Nov 24, 2020 9:55:43 AM
	 */
    @Override
    //@CacheEvict(cacheNames="TbLearningGardenContentLearningRecord", allEntries=true)
    public boolean save(TbLearningGardenContentLearningRecord entity) {
        return super.save(entity);
    }

	/**
	 * 通过id获取数据
	 * @author 苏小林
	 * @date Nov 24, 2020 9:55:43 AM
	 */
    @Override
    //@Cacheable(key = "#id",sync = true)
    public TbLearningGardenContentLearningRecord getById(Serializable id) {
        return super.getById(id);
    }

	/**
	 * 通过id删除数据
	 * @author 苏小林
	 * @date Nov 24, 2020 9:55:43 AM
	 */
    @Override
    //@CacheEvict(cacheNames="TbLearningGardenContentLearningRecord", allEntries=true)
    public boolean removeById(Serializable id) {
        return super.removeById(id);
    }

	/**
	 * 批量删除数据
	 * @author 苏小林
	 * @date Nov 24, 2020 9:55:43 AM
	 */
    //@CacheEvict(cacheNames="SysDict", allEntries=true)
    @Override
    public boolean removeByIds(Collection<? extends Serializable> idList) {
        return super.removeByIds(idList);
    }

	/**
	 * 分页查询数据
	 * @author 苏小林
	 * @date Nov 24, 2020 9:55:43 AM
	 */
    //@Cacheable(key = "#data",sync = true)
    public IPage<TbLearningGardenContentLearningRecord> selectPage(Map<String,Object> data) {
        int currentPage=1;
        if (!Objects.isNull(data.get("page"))) {
            currentPage=(Integer) data.get("page");
        }
        int pageSize=20;
        if (!Objects.isNull(data.get("size"))) {
            pageSize=(Integer) data.get("size");
        }

        TbLearningGardenContentLearningRecord entity = JSON.parseObject(JSON.toJSONString(data), TbLearningGardenContentLearningRecord.class);
        Page<TbLearningGardenContentLearningRecord> page = new Page(currentPage,pageSize);
        QueryWrapper<TbLearningGardenContentLearningRecord> wrapper = new QueryWrapper(entity);
        return super.selectPage(page, wrapper);
    }

	/**
	 * 查询所有数据
	 * @author 苏小林
	 * @date Nov 24, 2020 9:55:43 AM
	 */
    @Override
    //@Cacheable(value = "TbLearningGardenContentLearningRecord",sync = true)
    public List<TbLearningGardenContentLearningRecord> selectAll() {
        return super.selectAll();
    }

    /**
     * @Description: 学习统计按部门列表
     * @Author: liuqinghua
     * @Date: 2020/11/24
     */
    public IPage<LearningStatisticsListQuery> learningStatisticsList(LearningStatisticsListDto data) {
        Page<LearningStatisticsListQuery> page = new Page<>(data.getPage(),data.getSize());
        IPage<LearningStatisticsListQuery> learningStatisticsListQueryIPage = dao.learningStatisticsList(page, data);
        List<LearningStatisticsListQuery> records = learningStatisticsListQueryIPage.getRecords();
        // 需学习的总人数
        List<NeedLearningListQuery> needLearningList = tbGlobalUserMapper.getNeedLearningList();

        for (LearningStatisticsListQuery record: records) {
          String percentageNum = null;
            int needLearningNum =0;
            for (NeedLearningListQuery needLearning: needLearningList) {
                if (record.getLearnPeriod().getTime() >= needLearning.getArrivalDate().getTime()) {
                    needLearningNum++;
                }
            }
            BigDecimal multiply = record.getRecordNum().divide(new BigDecimal(needLearningNum),10,ROUND_HALF_DOWN).multiply(new BigDecimal(100));
            BigDecimal  num =multiply.setScale(2, RoundingMode.HALF_UP);
//            String div = StringUtils.div( record.getRecordNum(),new BigDecimal(needLearningNum), 2);
            percentageNum =num+"%";
            record.setPercentageNum(percentageNum);
        }
        learningStatisticsListQueryIPage.setRecords(records);

        return learningStatisticsListQueryIPage;
    }

    /**
     * @Description: 查看已学习的名单
     * @Author: liuqinghua
     * @Date: 2020/11/24
     */
    public IPage<LearnedListQuery> learnedList(LearningStatisticsListDto data) {
        Page<LearnedListQuery> page = new Page<>(data.getPage(),data.getSize());
        return dao.learnedList(page, data);
    }
    /**
     * 查询各部门今日学习人数
     * @author 苏小林
     * @date 2020/11/24 14:30
     * @param: month
     * @return: java.util.List<com.xhsj.user.hr.process.tbLearningGarden.vo.FindToDayStudyNumberVo>
     */
    public List<FindToDayStudyNumberVo> findToDayStudyNumber(String month) {
        LocalDate now = null;
        if (StringUtils.isBlank(month)) {
            now = LocalDate.now();
        }

        return dao.findToDayStudyNumber(month,now);
    }

    /**
     * 部门发布信息统计
     * @author 苏小林
     * @date 2020/11/24 17:48
     * @param: month
     * @return: java.util.List<com.xhsj.user.hr.process.tbLearningGarden.vo.FindToDayStudyNumberVo>
     */
    public List<FindToDayStudyNumberVo> findDeptPublishInfo(String month) {
        LocalDate now = null;
        if (StringUtils.isBlank(month)) {
            now = LocalDate.now();
        }

        return dao.findDeptPublishInfo(month,now);
    }

    /**
     * @Description: 学习园地首页数据统计
     * @Author: liuqinghua
     * @Date: 2020/11/25
     */
    public  Set<TbLearningGardenContentApply> learningGardenDataStatistics() {
        Long userId = UserUtils.getLoginAppUser().getUserId();
        // 学习内容
        QueryWrapper<TbLearningGardenContentApply> queryWrapper = new QueryWrapper();
        queryWrapper.eq("node_name","完结");
        queryWrapper.ge("learn_period", new Date());
        List<TbLearningGardenContentApply> tbLearningGardenContentApplies = tbLearningGardenContentApplyMapper.selectList(queryWrapper);
        // 学习记录
        Set<TbLearningGardenContentApply> listStatistics = new HashSet<>();
        Set<TbLearningGardenContentApply> listStatistics1 = new HashSet<>();
        Set<TbLearningGardenContentApply> listStatistics2 = new HashSet<>();
        List<TbLearningGardenContentLearningRecord> list = super.list();
        for (TbLearningGardenContentApply tbLearningGardenContentApply: tbLearningGardenContentApplies) {
            for (TbLearningGardenContentLearningRecord record: list) {
                if (Objects.equals(record.getApplyId(),tbLearningGardenContentApply.getId())&& !userId.equals(record.getCreateBy())) {
                    listStatistics.add(tbLearningGardenContentApply);
                }
                if (record.getApplyId().equals(tbLearningGardenContentApply.getId()) && userId.equals(record.getCreateBy())) {
                    listStatistics2.add(tbLearningGardenContentApply);
                }
                if (!record.getApplyId().equals(tbLearningGardenContentApply.getId())) {
                    listStatistics1.add(tbLearningGardenContentApply);
                }
            }
        }

        listStatistics.removeAll(listStatistics2);
        listStatistics1.removeAll(listStatistics2);
        listStatistics1.addAll(listStatistics);

        return listStatistics1;
    }
}
